package com.chrissy.music.system.service.impl;

import com.chrissy.music.common.cache.RedisCache;
import com.chrissy.music.common.cache.RedisKeys;
import com.chrissy.music.common.config.MusicConfig;
import com.chrissy.music.common.exception.ApiException;
import com.chrissy.music.common.request.SysCaptchaRequest;
import com.chrissy.music.common.response.SysCaptchaResponse;
import com.chrissy.music.system.service.SysCaptchaService;
import com.chrissy.music.system.service.SysConfigService;
import com.wf.captcha.ArithmeticCaptcha;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * @author Johnson
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class SysCaptchaServiceImpl implements SysCaptchaService {

    private final RedisCache redisCache;

    private final SysConfigService configService;

    private final MusicConfig musicConfig;


    /**
     * 生成验证码
     *
     * @return SysCaptchaResponse
     */
    @Override
    public SysCaptchaResponse generate() {
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        if (!captchaEnabled) {
            throw new ApiException(500, "获取验证码开关没有开启");
        }

        // 保存验证码信息
        String uuid = UUID.randomUUID().toString();

        String code = "";
        String image = null;

        // 生成验证码
        String captchaType = musicConfig.getCaptchaType();
        if ("math".equals(captchaType)) {
            ArithmeticCaptcha captcha = new ArithmeticCaptcha(120, 40);
            // 可设置支持的算法：2 表示只生成带加减法的公式
            captcha.setArithmeticString("2");
            image = captcha.toBase64();
            code = captcha.text();
        } else if ("char".equals(captchaType)) {
            SpecCaptcha captcha = new SpecCaptcha(120, 40);
            captcha.setLen(5);
            captcha.setCharType(Captcha.TYPE_DEFAULT);
            code = captcha.text();
            image = captcha.toBase64();
        }
        log.info("验证码为{}", code);
        String redisKey = RedisKeys.getCaptchaKey(uuid);
        redisCache.set(redisKey, code, 300);
        SysCaptchaResponse sysCaptchaResponse = new SysCaptchaResponse();
        sysCaptchaResponse.setImage(image);
        sysCaptchaResponse.setKey(uuid);
        return sysCaptchaResponse;
    }

    /**
     * 生成验证码
     *
     * @return SysCaptchaResponse
     */
    @Override
    public boolean validate(SysCaptchaRequest sysCaptchaRequest) {

        String captcha = getCache(sysCaptchaRequest.getUuid());
        // 效验成功
        return sysCaptchaRequest.getCode().equalsIgnoreCase(captcha);
    }

    private String getCache(String key) {
        key = RedisKeys.getCaptchaKey(key);
        String captcha = (String) redisCache.get(key);
        // 删除验证码
        if (captcha != null) {
            redisCache.delete(key);
        }

        return captcha;
    }

}
